package com.luoye.lj.platform.controller;

import com.luoye.lj.util.mvc.data.SimpleResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

@Controller
@RequestMapping("/system/translate")
public class TranslateController {

    private Logger logger = LoggerFactory.getLogger(TranslateController.class);

    @RequestMapping(value = "/translate")
    @ResponseBody
    public SimpleResponseBody translate(HttpServletRequest request, @RequestParam(value = "text", required = false,defaultValue = "") String text){
        SimpleResponseBody srb = new SimpleResponseBody();
        logger.debug("text->"+text);
        String content=translate(text);
        srb.setEntity(content);
        srb.setMsg("翻译成功");
        srb.setOk(true);
        return srb;
    }

    String translate(String cn) {
        try {
            cn=URLEncoder.encode(cn,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "http://translate.google.cn/translate_a/single?client=gtx&sl=zh-CN&tl=en&dt=t&q=googleq="+cn.trim(); //sl,tl参数可换成其他国家
        logger.debug("url->"+url);
        String content = sendGet(url);
        logger.debug("content->"+content);
        content = getTransString(content);
        logger.debug("content->"+content);
        return content;
    }
    String getTransString(String org) {
        String first = "\"googleq \\u003d ";
        String s = org.substring(org.indexOf(first)+first.length(), org.indexOf("\",\""));
        return s;
    }
    String sendGet(String url) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setRequestProperty("contentType", "UTF-8");
            // 建立实际的连接
            connection.connect();
            // 遍历所有的响应头字段
            // for (String key : map.keySet()) {
            // System.out.println(key + "--->" + map.get(key));
            // }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            //System.out.println("发送GET请求出现异常！" + e);
            result = new StringBuilder("{\"resCode\":\"1\",\"errCode\":\"1001\",\"resData\":\"\"}");
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return result.toString();
    }
}
